package com.itshizhan.itjidancideveloper.controller.ucenter;

import com.itshizhan.itjidancideveloper.dao.WordDao;
import com.itshizhan.itjidancideveloper.models.Word;
import com.itshizhan.itjidancideveloper.response.CodeMsgEnum;
import com.itshizhan.itjidancideveloper.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping("/ucenter/word")
public class WordController {

	@Autowired
	WordDao wordDao;

	@GetMapping("/test")
	String hellTest() {
		return "Hello Springboot with Kotlin";
	}

	@GetMapping("/search")
	Response<List<Word>> getListByKeyword(@RequestParam("q") String keyword){
		if (keyword.length() < 3) {
			return Response.fail(CodeMsgEnum.ERROR_PARAMETER);
		}
		return Response.success(wordDao.findByWordNameLike(keyword));
	}

	@GetMapping("/detail")
	Response<Word> getWordDetailById(@RequestParam("id") Long id) {
		Word word = wordDao.findById(id).orElse(null);
		return Response.success(word);

	}

	@PostMapping("/save")
	Response<Word> saveWord(@RequestBody Word word) {
		Word dbWord = wordDao.findById(word.getId()).orElse(null);
		if (dbWord!=null){
			dbWord.setMemoryMd(word.getMemoryMd());
			dbWord.setMemoryHtml(word.getMemoryHtml());
			Word save = wordDao.save(dbWord);
			return Response.success(save);
		}
		return Response.fail();

	}
}
